package com.qcby.admin.controller;


import cn.hutool.crypto.SecureUtil;
import com.qcby.admin.form.UserAddForm;
import com.qcby.admin.form.UserChangeForm;
import com.qcby.admin.form.UserPageForm;
import com.qcby.admin.form.UserUpdateForm;
import com.qcby.admin.model.SysRole;
import com.qcby.admin.model.SysUser;
import com.qcby.admin.model.SysUserRole;
import com.qcby.admin.service.SysRoleService;
import com.qcby.admin.service.SysUserRoleService;
import com.qcby.admin.service.SysUserService;
import com.qcby.admin.vo.UserListVo;
import com.qcby.admin.vo.UserUpdateVo;
import com.qcby.framwork.utils.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2024-09-15
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysUserRoleService userRoleService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /*加载用户列表*/
    @GetMapping("/list")
    public ResponseResult list( UserPageForm userPageForm){
        UserListVo userListVo=userService.userList(userPageForm);
        return ResponseResult.okResult(userListVo);
    }

    /*修改用户的状态*/
    @PutMapping("/changeStatus")
    public ResponseResult changeStatus(@RequestBody UserChangeForm userChangeForm){
        SysUser user=new SysUser();
        user.setId(userChangeForm.getUserId());
        user.setStatus(userChangeForm.getStatus());
        boolean updateById = userService.updateById(user);
        if(!updateById) return ResponseResult.errorResult(500,"修改用户状态失败");
        return ResponseResult.okResult();

    }
     /*
      * 新增用户
      * 1.新增用户密码加密存储
      * 2.用户名不能为空，否则提示：必须填写用户名
      * */
    @PostMapping
    public ResponseResult add(@RequestBody UserAddForm userAddForm){
        //创建user对象
        SysUser user=new SysUser();
        //将表单中的数据复制到user对象中
        BeanUtils.copyProperties(userAddForm,user);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        //新增用户密码加密存储
        String password = passwordEncoder.encode(userAddForm.getPassword());
        user.setPassword(password);
        //用户名不能为空，否则提示：必须填写用户名
        if(!StringUtils.hasText(user.getUserName())) return ResponseResult.errorResult(500,"必须填写用户名");
        boolean saveUser = userService.save(user);
//        if(!saveUser) return ResponseResult.errorResult(500,"新增用户失败");

        //添加用户对应的角色信息
        SysUserRole userRole=new SysUserRole();
        List<String> roleIds = userAddForm.getRoleIds();
        for (String roleId : roleIds) {
            Long roleId1 = Long.valueOf(roleId);
            userRole.setRoleId(roleId1);
            userRole.setUserId(user.getId());
            boolean saveUserRole = userRoleService.save(userRole);
            if(!saveUserRole) return ResponseResult.errorResult(500,"新增用户失败");

        }
        return ResponseResult.okResult();
    }
//        userRole.setUserId(user.getId());
//        userRole.setRoleId(userAddForm.getRoleId());
//        boolean saveRole=userRoleService.save(userRole);
//        if(saveUser&&saveRole) return ResponseResult.okResult();


    /*回显用户信息*/
    @GetMapping("/{userId}")
    public ResponseResult info(@PathVariable Long userId){
        //根据id查询用户信息
        SysUser user=userService.getById(userId);
        UserUpdateVo userUpdateVo=new UserUpdateVo();
        userUpdateVo.setUser(user);

        List<SysRole> list = userRoleService.listUserRole(userId);
        userUpdateVo.setRoles(list);
        List<Long> roleIds=userRoleService.selectRoleIds(userId);
        userUpdateVo.setRoleIds(roleIds);
        if(user==null) return ResponseResult.errorResult(500,"用户不存在");
        return ResponseResult.okResult(userUpdateVo);
    }

    /*修改用户信息*/
    @PutMapping
    public ResponseResult update(@RequestBody UserUpdateForm userUpdateForm){
        SysUser user=new SysUser();
        BeanUtils.copyProperties(userUpdateForm,user);
        //根据id修改用户信息
        boolean updateById=userService.updateById(user);
        if(!updateById) return ResponseResult.errorResult(500,"修改用户失败");

        //先删除当前用户的相关联角色
        userRoleService.removeByRoleId(user.getId());
        //插入新的角色
        SysUserRole userRole=new SysUserRole();
        List<String> roleIds = userUpdateForm.getRoleIds();
        for (String roleId : roleIds) {
            Long roleId1 = Long.valueOf(roleId);
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleId1);
            boolean saveUserRole = userRoleService.save(userRole);
            if(!saveUserRole) return ResponseResult.errorResult(500,"修改用户所对应的角色失败");
        }
         return ResponseResult.okResult();
    }

    /*删除用户*/
    @DeleteMapping("/{id}")
    public ResponseResult del(@PathVariable Long id){
        boolean removeById = userService.removeById(id);
        //删除用户对应的角色
        userRoleService.removeByRoleId(id);
        if(removeById) return ResponseResult.okResult();
        return ResponseResult.errorResult(500,"删除用户失败");
    }
}

